# -*- utf-8 -*-
__author__ = "Canotf"

import datetime

from sqlalchemy import Column, types, ForeignKey, create_engine, MetaData, Table, inspect
from sqlalchemy.ext.automap import automap_base

from sqlalchemy.orm import relationship, declarative_base, sessionmaker

from wangshihe.settings import MY_DEBUG


def get_engine():
    if MY_DEBUG:
        engine = create_engine("mysql+pymysql://root:123456@127.0.0.1/wsh_bigdata", encoding="utf-8", echo=True,
                               max_overflow=5)
    else:
        engine = create_engine("mysql+pymysql://root:wanshihe66..@127.0.0.1/wsh_bigdata", encoding="utf-8", echo=True,
                               max_overflow=5)
    return engine


def get_session(engine):
    DBSession = sessionmaker(bind=engine)
    session = DBSession()
    return session


def get_tables():
    Base = declarative_base()
    Base.metadata.reflect(get_engine())
    tables = Base.metadata.tables
    return tables


def get_fields(table_name):
    table = Table(table_name, MetaData(), autoload=True, autoload_with=get_engine())
    return table.c


def get_primary_keys(table_name):
    engine = get_engine()
    metadata = MetaData(bind=engine)
    metadata.reflect(bind=engine)
    Base = automap_base(metadata=metadata)
    Base.prepare()

    # ow就是overwatch表对应的内
    ow = getattr(Base.classes, table_name)

    # 获取主键
    primary_keys = inspect(ow).primary_key
    return primary_keys


BaseTable = declarative_base()  # 生成orm基类


class Expand:
    def to_dict(self):
        model_dict = dict(self.__dict__)
        del model_dict['_sa_instance_state']
        return model_dict


class Account(BaseTable, Expand):
    """账号托管"""
    # 账号状态
    ACCOUNT_STATUS = {
        'SUCCESS': {
            'code': 200,
            'message': '正常'
        },
        'WARING': {
            'code': 400,
            'message': '账号密码错误'
        },
        'ERROR': {
            'code': 200,
            'message': '封禁中'
        },
        'UNKNOWN': {
            'code': 200,
            'message': '未知错误'
        }
    }
    # --------------------------------------------------------------------------------
    __tablename__ = "account"
    id = Column(types.Integer, primary_key=True, comment='主键自增')
    create_time = Column(types.DateTime, comment='创建时间', default=datetime.datetime.now)
    update_time = Column(types.DateTime, comment='更新时间', default=datetime.datetime.now, onupdate=datetime.datetime.now)
    # --------------------------------------------------------------------------------
    name = Column(types.Text, comment='登录名')
    password = Column(types.Text, comment='密码')
    platform_id = Column(types.Integer, ForeignKey('platform.id'), comment='哪个平台的账号')
    platform = relationship('Platform', backref='Account')
    status = Column(types.SmallInteger, default=ACCOUNT_STATUS.get('SUCCESS').get('code'), comment="账号状态")

    def __repr__(self):
        return '<Name: %s Password: %s Platform: %s>' % (self.name, self.password, self.platform.name)


class Platform(BaseTable, Expand):
    """平台信息表"""
    # --------------------------------------------------------------------------------
    __tablename__ = "platform"
    id = Column(types.Integer, primary_key=True, comment='主键自增')
    create_time = Column(types.DateTime, comment='创建时间', default=datetime.datetime.now)
    update_time = Column(types.DateTime, comment='更新时间', default=datetime.datetime.now, onupdate=datetime.datetime.now)
    # --------------------------------------------------------------------------------
    name = Column(types.String(255), comment="平台的名称")
    home_url = Column(types.Text, comment='主页的链接')
    login_url = Column(types.Text, comment='登陆地址的链接')
    label = Column(types.String(255), comment="标记名称")

    def __repr__(self):
        return '<Task: %s Label: %s>' % (self.name, self.label)


class Brand(BaseTable, Expand):
    """任务线程表"""
    # --------------------------------------------------------------------------------
    __tablename__ = "brand"
    id = Column(types.Integer, primary_key=True, comment='主键自增')
    create_time = Column(types.DateTime, comment='创建时间', default=datetime.datetime.now)
    update_time = Column(types.DateTime, comment='更新时间', default=datetime.datetime.now, onupdate=datetime.datetime.now)
    # --------------------------------------------------------------------------------
    name = Column(types.String(255), comment="任务名称")
    platform_id = Column(types.Integer, ForeignKey('platform.id'), comment='哪个平台的任务')
    platform = relationship('Platform', backref='brand_tasks')

    def __repr__(self):
        return '<Task %s>' % self.name


class ShopInfo(BaseTable, Expand):
    """淘宝商品信息表"""
    # --------------------------------------------------------------------------------
    __tablename__ = "shop_info"
    id = Column(types.Integer, primary_key=True, comment='主键自增')
    create_time = Column(types.DateTime, comment='创建时间', default=datetime.datetime.now)
    update_time = Column(types.DateTime, comment='更新时间', default=datetime.datetime.now, onupdate=datetime.datetime.now)
    # --------------------------------------------------------------------------------
    image = Column(types.Text, comment="展示的图片")
    money = Column(types.Float, comment="单价")
    sales = Column(types.Integer, comment="销量，也就是付款人数")
    message = Column(types.Text, comment="说明和标题")
    title = Column(types.Text, comment="说明和标题")
    # free_shipping = Column(types.Boolean, default=False, comment="是否包邮")
    is_tianmao = Column(types.Boolean, default=False, comment="是否为天猫")
    is_xinpin = Column(types.Boolean, default=False, comment="是否为新品")
    # is_advertise = Column(types.Boolean, default=False, comment="是否为广告")
    link = Column(types.Text, comment="商品详情地址")
    brand_name = Column(types.Text, comment="店铺名称")
    region = Column(types.Text, comment='发货地址')
    # --------------------------------------------------------------------------------
    platform_id = Column(types.Integer, ForeignKey('platform.id'), comment='哪个平台的任务')
    platform = relationship('Platform', backref='shop_infos')
    brand_id = Column(types.Integer, ForeignKey('brand.id'), comment='哪个品牌')
    brand = relationship('Brand', backref='shop_infos')
    from_url = Column(types.Text, comment="从哪个页面来的数据")

    def __repr__(self):
        return '<Shop %s>' % self.title


class AccountLoginLog(BaseTable, Expand):
    """登录日志表"""
    # --------------------------------------------------------------------------------
    __tablename__ = "account_login_log"
    id = Column(types.Integer, primary_key=True, comment='主键自增')
    create_time = Column(types.DateTime, comment='创建时间', default=datetime.datetime.now)
    update_time = Column(types.DateTime, comment='更新时间', default=datetime.datetime.now, onupdate=datetime.datetime.now)
    # --------------------------------------------------------------------------------
    platform_id = Column(types.Integer, ForeignKey('platform.id'), comment='哪个平台的任务')
    platform = relationship('Platform', backref='account_login_log')
    account_id = Column(types.Integer, ForeignKey('account.id'), comment='哪个平台的任务')
    account = relationship('Account', backref='account_login_log')

    def __repr__(self):
        return '<Platform: %s Account:%s>' % (self.platform.name, self.account.name)


if __name__ == '__main__':
    BaseTable.metadata.create_all(get_engine())
